import { constantRoutes } from '@/router'
import Layout from '@/layout/index'
import http from '@/utils/http-request'
import { handleTree } from '@/utils/common'

const permission = {
  state: {
    routes: [],
    addRoutes: []
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes
      state.routes = constantRoutes.concat(routes)
    }
  },
  actions: {
    // 生成路由
    GenerateRoutes({ commit }) {
      return new Promise(resolve => {
        http.get('/sysResources/list').then(res => {
          const treeMenus = handleTree(res.data)
          const menus = buildMenus(treeMenus)
          const accessedRoutes = filterAsyncRouter(menus)
          // accessedRoutes.push({ path: '*', redirect: '/404', hidden: true })
          commit('SET_ROUTES', accessedRoutes)
          resolve(accessedRoutes)
        })
      })
    }
  }
}

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap) {
  return asyncRouterMap.filter(route => {
    if (route.component) {
      // Layout组件特殊处理
      if (route.component === 'Layout') {
        route.component = Layout
      } else {
        route.component = loadView(route.component)
      }
    }
    if (route.meta && route.meta.icon) {
      route.meta.icon = loadIcon(route.meta.icon)
      route.meta.icon1 = loadIcon(route.meta.icon1)
      route.meta.icon2 = selectIcon(route.meta.icon2)
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    return true
  })
}

export const loadView = (view) => { // 路由懒加载
  return (resolve) => require([`@/views/${view}`], resolve)
}
export const loadIcon = (icon) => { // icon转化
  return require(`@/assets/images/topMenu/${icon}.png`)
}
export const selectIcon = (icon) => { // icon转化
  return require(`@/assets/images/menuWhite/${icon}.png`)
}

function buildMenus(menus) {
  const routers = []
  menus.map(item => {
    const router = {}
    router.hidden = item.status == '1' ? true : false
    router.path = item.url
    router.component = getComponent(item.zjurl)
    router.meta = {}
    router.meta.title = item.name
    if (item.icon) {
      router.meta.icon1 = item.icon
      router.meta.icon2 = item.icon
      router.meta.icon = item.icon.replace('1', '')
    } else {
      router.meta.icon1 = 'default-icon'
      router.meta.icon2 = 'default-icon'
      router.meta.icon = item.icon.replace('1', '')
    }
    if (item.redirecturl) {
      router.redirect = item.redirecturl
    }
    const cmenus = item.children
    if (cmenus) {
      router.children = buildMenus(cmenus)
    }
    routers.push(router)
  })
  return routers
}

function getComponent(component) {
  if (!component) {
    return 'Layout'
  } else {
    return component
  }
}

export default permission
